public class 链表 {

    public static ListNode createNode(int n) {
        ListNode head = new ListNode(0);
        ListNode h = head;
        for (int i = 1; i < n; i++) {
            h.next = new ListNode(i);
            h = h.next;
        }
        return head;
    }

    public static void printList(ListNode head) {
        ListNode h = head;
        if (head == null)
            System.out.println("null");
        else {
            while (h.next != null) {
                System.out.print(h.val + " ");
                h = h.next;
            }
            System.out.println(h.val);
        }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode h = head;
        int l = 0;
        while (h != null) {
            l++;
            h = h.next;
        }
        if (l == n)
            return head.next;
        h = head;
        for (int i = 1; i < l - n; i++) {
            h = h.next;
        }
        h.next = h.next.next;
        return head;
    }

    //合并链表
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode temp = new ListNode();
        ListNode res = temp;
        int m = lists.length;
        int count = 0;
        while (count < m) {
            int min_index = 0;
            for (int i = 0; i < m; i++) {
                //双min
                if (lists[i] == null)
                    count++;
                else if (lists[min_index] == null || lists[i].val < lists[min_index].val) {
                    min_index = i;
                }
            }
            res.next = lists[min_index];
            res = res.next;
            if (lists[min_index] != null)
                lists[min_index] = lists[min_index].next;
        }
        return temp.next;
    }

    public static void main(String[] args) {
        ListNode head = createNode(5);
        printList(head);
        head = removeNthFromEnd(head, 1);
        printList(head);
    }
}



